package cool.tianyou.blue.bird.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Icon;
import android.os.Build;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.text.TextUtils;
import android.util.Base64;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cool.tianyou.blue.bird.Filter;
import cool.tianyou.blue.bird.constant.Constant;
import cool.tianyou.blue.bird.factory.MessageFactory;
import cool.tianyou.blue.bird.model.CommonMessage;
import cool.tianyou.blue.bird.model.NotificationData;
import cool.tianyou.blue.bird.model.PushedNotification;
import cool.tianyou.blue.bird.util.Util;

@SuppressLint("OverrideAbstract")
public class NotificationService extends NotificationListenerService {
    Map<String, Bitmap> appIcons = new HashMap<>();

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    private Map<String, Bitmap> getPkgListNew(Context context) {
        Map<String, Bitmap> pkgIcon = new HashMap<>();
        try {
            List<PackageInfo> packageInfos = context.getPackageManager().getInstalledPackages(PackageManager.GET_ACTIVITIES |
                    PackageManager.GET_SERVICES);
            for (PackageInfo info : packageInfos) {
                String pkg = info.packageName;
                Drawable drawable = info.applicationInfo.loadIcon(context.getPackageManager());
                pkgIcon.put(pkg, drawableToBitmap(drawable));
            }
        } catch (Throwable t) {
            t.printStackTrace();
            ;
        }
        return pkgIcon;
    }

    public Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    @RequiresApi(api = Build.VERSION_CODES.P)
//    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        try {
            if (sbn.getNotification().tickerText != null) {
                Bundle extras = sbn.getNotification().extras;
                //通知包名
                String notificationPkg = sbn.getPackageName();
                Icon largeIcon = sbn.getNotification().getLargeIcon();
                Bitmap icon = sbn.getNotification().largeIcon;
                //获取应用图标
                if (icon == null) {
                    icon = appIcons.getOrDefault(notificationPkg, getPkgListNew(this).get(notificationPkg));
                    largeIcon = Icon.createWithAdaptiveBitmap(icon);
                }
                String base64 = "";
                if (icon != null) {
                    base64 = bitmapToBase64String(resizeBitmap(80, 80, icon), Bitmap.CompressFormat.PNG, 100);
                    //QQ 音乐默认图丢弃
                    if (base64.equals("iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAAAc2SURBVHic7ZttV9pKF4bvPQkBobyoBdQHELV+6Efb//8X/ANtbanIg4CwFAwKSfb54Jo04a2BTETPybVWl5pOZiZ39p6XPTsEAF++fGkQUQ0xgWHmzuXlZZkuLi6aQoj/bbtD7xFmbolYvM0hoiOx7U68d2IBQxILGJJYwJDEAoYkFjAksYAhiQUMSSxgSGIBQxILGJJYwJDEAoYkFjAksYAh0bfdAWaGEAKO4wAADMNAMpmErusgIgCAbduYTCawbRvT6dR3LwAQERzHgaZpICLYtu3eGzVbEVA+uGR3dxf7+/sgIjAzdF13yzGzK5AUxbIsDAYD3N3dueWICIVCAaZpwrbtV3uWrQgohMDOzg7K5TIMw5izFikIgIU/dV1HqVRCJpNBs9l0X0i5XEa73cbz8/O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8G7FtG/1+H51OZ+H5hxciQq/XQ6lUWrsdIlK6s1HmwsPh0E3HWMcqHMeBaZq4urpCr9fzHT6tQgiBHz9+bNRXlQfvygR8enra6L7RaIRGo7F2PgsRYTqdru2O6xyXBkHpJOI9hw3CaDTC7e3txm0SEdrtduA2mRmmafoSlMKiVMBms7nWWUWr1QqdSSWXNUEgIvz+/VvJnl2idB34+PgY2ApN01SynGBm9Hq9QGUty1Kyk/GidCtHROh2u4EEfHh4UGYJk8kkULkw68dlKN8LDwaDv75lZla6FgvyIp6fn30ZXcraVlob/oyFq8LmqmdCy7JW1sfMuL6+fj8H66ZpYjQaLRWRmTc6vVvGKgtkZtzd3SndvvnaVlmZdwfRbrdXTijZbHZuz7spyxKMgJf1aa/Xiyz4EGl2VqPRWOheRIR0Oq3kEErTtIXWzMyYTqeRua4k0nCWZVm4urpaaIlE5KafbQozo1KpzAVIpXjfv3+PPOE88nigbdv49u2bm54rkfl9lUplLQvxun25XF54QDQcDn375GUJmiqIXEDZ6evra3Q6nbnrmUwG1WoViUQisJCJRAJnZ2cLsxba7TZarVZkgs1CX79+fdXQLhHh+PgYqVRqLpHo8fER3W4Xk8lkLlFcCAHDMHBwcDBndTKi02633dlWChd15PrVBZQPpGkaKpWKe3Q5m3Ul82OAPylq8nd5XQiB4XCIm5sb34c4spy3vah49Q9tvAdEjUYDAFAoFLC3t4dEIuE7xpxNzpT3PT09od/v4+HhYa7e2fJRs9Vv5eRD39/f4/7+HkQvn3Qlk0lfFhURwbIsjMfjufS3bbP1jw0l3jFvOp264+Ait3xLvBkBZ8V5i2ItYvs+8M6JBQzJm3FhL28l6yAIsQWGJBYwJLGAIYkFDEksYEhiAUMSCxiSWMCQxAKGJBYwJMJxHLXfUf2HYOb/EwC6uLj4LYSobLtD7wlm7l1eXhb/AYc3a2iT46FAAAAAAElFTkSuQmCC")) {
                        return;
                    }
                }
                // 通知标题
                String notificationTitle = "";
                if (extras.getString(Notification.EXTRA_TITLE) != null) {
                    notificationTitle = extras.getString(Notification.EXTRA_TITLE).toString();
                }

                // 通知内容
                String notificationText = "";
                if (extras.getString(Notification.EXTRA_TEXT) != null) {
                    notificationText = extras.getString(Notification.EXTRA_TEXT).toString();
                }
                int notificationId = sbn.getId();
                PushedNotification pushedNotification = Constant.PUSHED_NOTIFICATION_ID.get(notificationId);
                if (pushedNotification != null && pushedNotification.completeEquals(notificationTitle, notificationText)) {
                    return;
                }
                Constant.PUSHED_NOTIFICATION_ID.put(notificationId, new PushedNotification(notificationId, notificationTitle, notificationText));

                String finalNotificationTitle = notificationTitle;
                String finalNotificationText = notificationText;
                if (Constant.defaultFilters.stream().noneMatch(filter -> filter.match(notificationPkg, finalNotificationTitle, finalNotificationText))) {
                    CommonMessage commonMessage = MessageFactory.notificationMessage(largeIcon, "data:image/png;base64," + base64, notificationTitle, notificationText, notificationPkg);
                    Util.sendMessage(commonMessage, this);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(NotificationService.this, "不可解析的通知", Toast.LENGTH_SHORT).show();
        }

    }

    public Bitmap resizeBitmap(float newWidth, float newHeight, Bitmap bitmap) {

        Matrix matrix = new Matrix();
        matrix.postScale(newWidth / bitmap.getWidth(),

                newHeight / bitmap.getHeight());

        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, true);

        return newBitmap;
    }

    public static String bitmapToBase64String(Bitmap bmp, Bitmap.CompressFormat format, int quality) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(format, quality, baos);
        byte[] bytes = baos.toByteArray();
        return Base64.encodeToString(bytes, Base64.NO_WRAP);
    }


    public String imageToBase64(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try {
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
//            result = cool.tianyou.blue.bird.codec.binary.Base64.encodeBase64String(data);
            result = Base64.encodeToString(data, Base64.NO_WRAP);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


}
